<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content add-temp">
      <e-heading grade='1'>{{$route.query.trainPlanId ? '编辑' : '新增'}}训练计划模板</e-heading>
      <el-form ref="form" v-bind="getFormProps({labelWidth: '100px'})" :model="form">
        <el-row>
          <el-col :span="24">
            <el-form-item label="课时主题：" prop="topic" :rules="[
                {required: true, message: '请输入主题名称'},
                Object.assign({
                  trigger: 'blur',
                  validator: form.topic !== oldTopic || $route.query.type === TYPE_ENUM.ADD ? validator.rule.checkTopic.validator.bind(this) : ''})
              ]">
              <el-input v-model="form.topic" :maxlength="25" number-word style="width: 50%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10" >
            <el-form-item label="运动类型：" label-width="100px">
              <el-select v-model="form.sportType" placeholder="请选择运动类型" style="width:95%;" size="small" clearable>
                <el-option
                  v-for="item in mode_sport_list"
                  :key="item.fieldValue"
                  :label="item.fieldName"
                  :value="item.fieldValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" >
            <el-form-item label="" label-width="0">
              <el-input size="small" v-model="form.keyword" placeholder="请输入搜索内容" style="width: 98%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="20px">
              <el-button size="small" type="primary-plain" native-type="submit">搜索</el-button>
              <el-button type="link" style="line-height:36px;" @click="handleShowSearch">更多筛选 <i :class="isShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-collapse-transition>
        <search-card v-show="isShow" @updateSearch="handleSearch" :serachQuery="serachQuery" :keys="serachQuery" v-if="isUpdate"></search-card>
      </el-collapse-transition>
      <e-heading grade='1'>训练方式列表</e-heading>
      <div class="method-list" v-if="mode_style_list.list && mode_style_list.list.length > 0">
        <el-checkbox-group v-model="selectedList" @change="handleSelectedList">
          <el-checkbox v-for="(item, index) in mode_style_list.list" :key="index" :label="item.id">
            <mode-plan 
              :singleItem="item" 
              @detail="handleDetail" 
              :modeSportList="mode_sport_list"
              :handleEd="0"/>
          </el-checkbox>
        </el-checkbox-group>
        <el-pagination
          v-bind="getPaginationProps(mode_style_list)"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          >
        </el-pagination>
        <div class="selectedNum">已选<span>{{selectedList.length}}</span>个</div>
        <div class="button-box">
          <el-button type="normal" @click="handleBack">返 回</el-button>
          <el-button type="primary" @click="handleCancelSelected" :disabled="selectedList.length == 0">取消选择</el-button>
          <el-button type="primary" @click="handlePreview" :disabled="selectedList.length == 0">
            预 览
          </el-button>
          <el-button type="primary" @click="handleNext" :disabled="selectedList.length == 0">下一步</el-button>
        </div>
      </div>
      <!--无数据提示-->
      <e-placeholder text="暂无数据" src="/static/images/training/no_course.png" v-else></e-placeholder>
    </div>
  </div>
</template>

<script>
import {pagingList} from 'utils/mixins'
import { TYPE_ENUM } from './constant'
import SearchCard from '../mode/components/SearchCard'
import { ModeData } from '../mode/modeData'
import { mapGetters } from 'vuex'
import ModePlan from './components/ModePlan'
import validator from 'utils/validator'
import api from 'api/trainingProgram'

export default {
  mixins: [pagingList],
  components: {
    SearchCard,
    ModePlan
  },
  computed: {
    ...mapGetters({
      mode_sport_list: 'mode_sport_list',
      mode_style_list: 'mode_style_list'
    })
  },
  data () {
    return {
      TYPE_ENUM,
      validator,
      isShow: false,
      selectedList: [],
      setData: ModeData,
      serachQuery: {},
      query: this.getQuery(),
      form: {
        topic: '',
        sportType: '',
        keyword: ''
      },
      oldTopic: '',
      planObjList: [],
      isUpdate: false
    }
  },
  mounted () {
    this.closeBrowser()
    this.isUpdate = true
    this.isShow = this.$route.query.isShow
    this.form.sportType = this.$route.query.sportType ? Number(this.$route.query.sportType) : ''
    this.form.keyword = this.$route.query.trainingName
    this.query.auditStatus = 2
    this.serachQuery.techDomainInfos = this.$route.query.techDomainInfos ? this.$route.query.techDomainInfos.split(',') : ['']
    this.serachQuery.trainingDurations = this.$route.query.trainingDurations ? this.$route.query.trainingDurations.split(',') : ['']
    this.serachQuery.teachingInfos = this.$route.query.teachingInfos ? this.$route.query.teachingInfos.split(',') : ['']
    this.serachQuery.trainingIntensions = this.$route.query.trainingIntensions ? this.$route.query.trainingIntensions.split(',') : ['']
    this.serachQuery.ageInfos = this.$route.query.ageInfos ? this.$route.query.ageInfos.split(',') : ['']
    this.serachQuery.scopeInfos = this.$route.query.scopeInfos ? this.$route.query.scopeInfos.split(',') : ['']
    this.$store.dispatch('mode_sport_list', '')
    if (this.$route.query.type === TYPE_ENUM.EDIT) {
      api.searchStyleList({auditStatus: 2, page: 1, rows: 1000}).then(res => { // 所有审核通过的训练方式
        this.planObjList = res.data.list
      })
    }
  },
  destroyed () { // 离开页面时关闭提示
    window.onbeforeunload = null
  },
  watch: {
    'form.sportType': function (val) {
      this.query.sportType = val
    },
    'form.keyword': function (val) {
      this.query.trainingName = val
    },
    'isShow': function (val) {
      this.query.isShow = Boolean(val)
    },
    'query.sportType': function (val) { // 新增和编辑搜索的接口切换
      if (!val && this.$route.query.trainPlanId) {
        this.query.type = TYPE_ENUM.EDIT
      } else {
        this.query.type = TYPE_ENUM.ADD
      }
    },
    'query.trainingName': function (val) { // 新增和编辑搜索的接口切换
      if (!val && this.$route.query.trainPlanId) {
        this.query.type = TYPE_ENUM.EDIT
      } else {
        this.query.type = TYPE_ENUM.ADD
      }
    }
  },
  methods: {
    fetch (query) {
      this.query.sportType = this.form.sportType
      this.query.trainingName = this.form.keyword
      this.$store.dispatch('mode_style_list', this.query).then(_ => { // vuex中action做了处理
        if (this.query.type === TYPE_ENUM.EDIT) {
          this.form.topic = this.oldTopic = this.$store.getters.mode_style_list.list[0].topic
          this.$store.getters.mode_style_list.list.forEach(item => {
            if (item.selected) {
              return this.selectedList.push(item.id)
            }
          })
          this.selectedList = Array.from(new Set(this.selectedList)) // 数组去重
        }
      })
    },
    handleShowSearch () {
      this.isShow ? this.isShow = false : this.isShow = true
    },
    handleSearch (val) { // 搜索
      let newData = {}
      for (let i in val) {
        newData[i] = val[i].join(',')
      }
      if (Object.values(val).filter(item => { return item.join('') }).length === 0 && this.$route.query.trainPlanId) { // 新增和编辑搜索的接口切换
        this.query.type = TYPE_ENUM.EDIT
      } else {
        this.query.type = TYPE_ENUM.ADD
      }
      Object.assign(this.query, newData)
      this.fetch(this.query)
    },
    handleBack () {
      this.$msgbox({
        title: '温馨提示',
        message: <div>
          <div>训练计划模板尚未提交</div>
          <div style="margin-top: 10px">确定要放弃编辑吗？</div>
        </div>,
        cancelButtonText: '留在此页',
        confirmButtonText: '确定离开',
        showCancelButton: true,
        type: 'warning'
      }).then(res => {
        history.back()
      }).catch(() => {})
    },
    handleCancelSelected () {
      this.selectedList = []
    },
    handlePreview () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.selectedList.length < 16) {
            let temObj = []
            let allStyleList = this.planObjList.length > 0 ? this.planObjList : this.mode_style_list.list // 编辑时取的是planObjList
            allStyleList.forEach(item => {
              if (this.selectedList.includes(item.id)) {
                return temObj.push(item)
              }
            })
            this.$store.commit('TEMPORARY_DETAIL_DATA', {topic: this.form.topic, selectedList: temObj}) // 储存临时的数据预览
            this.$router.push({name: 'preview', query: {type: TYPE_ENUM.PREVIEW}})
          } else {
            this.$message({
              type: 'error',
              message: '最多可选择15个训练方式！'
            })
          }
        }
      })
    },
    handleNext () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.selectedList.length < 16) {
            let temObj = []
            let allStyleList = this.planObjList.length > 0 ? this.planObjList : this.mode_style_list.list // 编辑时取的是planObjList
            allStyleList.forEach(item => {
              if (this.selectedList.includes(item.id)) {
                return temObj.push(item)
              }
            })
            this.$store.commit('TEMPORARY_DETAIL_DATA', {
              topic: this.form.topic,
              selectedList: temObj,
              type: this.$route.query.trainPlanId ? TYPE_ENUM.EDIT : TYPE_ENUM.ADD
            })
            this.$router.push({path: '/training/trainingprogram/plan/detail', query: {type: TYPE_ENUM.DETAIL, id: this.$route.query.trainPlanId}})
          } else {
            this.$message({
              type: 'error',
              message: '最多可选择15个训练方式！'
            })
          }
        }
      })
    },
    handleDetail (row) { // 训练方式详情
      this.$router.push({path: '/training/trainingprogram/mode/show', query: {id: row.data.id}})
    },
    closeBrowser () { // 关闭当前网页
      window.onbeforeunload = () => {
        return false
      }
    },
    handleSelectedList (val) {
      if (val && val.length > 15) {
        this.$message({
          type: 'error',
          message: '最多可选择15个训练方式！'
        })
      }
    }
  }
}
</script>

<style lang="scss">
  .add-temp {  
    .method-list{
      padding-top: 20px;
      .el-checkbox {
        margin-bottom: 15px;
      }
      .selectedNum {
        color: #666;
        span {
          color:#24c881;
          padding: 0 3px;
        }
      }
    }
  }
</style>
